package controllers;

import doa.CategoryDAO;
import doa.ProductDAO;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.hibernate.Session;
import models.Category;
import org.hibernate.*;
import service.HibernateUtil;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CategoryController extends HttpServlet {

    private String address = "";
    String redirect = "false";
    public static HttpSession session_user;

    public ArrayList getPaths() {
        ArrayList paths = new ArrayList();
        paths.add(0, "/category");
        paths.add(1, "/manage/category/new");
        paths.add(2, "/manage/category/overview");
        paths.add(3, "/manage/category/edit");
        paths.add(4, "/manage/category/delete");

        return paths;
    }

    public ArrayList getPathsJSP() {
        ArrayList paths_jsp = new ArrayList();
        paths_jsp.add(0, "/category/category.jsp");
        paths_jsp.add(1, "/manage/category/new.jsp");
        paths_jsp.add(2, "/manage/category/overview.jsp");
        paths_jsp.add(3, "/manage/category/new.jsp");
        paths_jsp.add(4, "/manage/category/overview.jsp");
        return paths_jsp;
    }
    /*
     * HTTP GET request
     */

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();

        String path = request.getServletPath();
        session_user = request.getSession();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();

        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // ---------------- /category/category --------------------
                    if (i == 0) {

                        List<Category> category_list = CategoryDAO.getAllCategories();
                        request.setAttribute("pageTitle", "Category");
                        request.setAttribute("categoryList", category_list);
                        request.setAttribute("amountOfCategories", category_list.size());

                    } // ---------------- /manage/category/new --------------------
                    else if (i == 1) {
                        System.out.println("new");

                        List<Category> category_list = CategoryDAO.getAllCategories();
                        request.setAttribute("category_list", category_list);
                        request.setAttribute("amountOfCategories", category_list.size());


                    } // ---------------- /manage/category/overview --------------------
                    else if (i == 2) {

                        List<Category> category_list = CategoryDAO.getAllCategories();
                        request.setAttribute("pageTitle", "Category");
                        request.setAttribute("categoryList", category_list);
                        request.setAttribute("amountOfCategories", category_list.size());
                    }// ---------------- /manage/category/edit --------------------
                    else if (i == 3) {
                        int category_id = Integer.parseInt(request.getParameter("categoryid"));
                        List<Category> category_list = CategoryDAO.getAllCategories();
                        Category category = CategoryDAO.getCategory(category_id);
                        request.setAttribute("category", category);
                        request.setAttribute("category_list", category_list);
                        request.setAttribute("amountOfCategories", category_list.size());
                    }// ---------------- /manage/category/delete --------------------
                    else if (i == 4) {
                        int id = Integer.parseInt(request.getParameter("categoryid"));
                        CategoryDAO.deleteCategory(id);
                        response.sendRedirect(response.encodeRedirectURL("overview"));
                        return;
                    }

                }
            } catch (Exception E) {
            }
        }
//        request.setAttribute("usertypes", UserClass.getUsertypes());
        if (redirect == "true") {
            response.sendRedirect(response.encodeRedirectURL("../users"));
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

        ArrayList paths = getPaths();
        ArrayList paths_jsp = getPathsJSP();
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        Transaction tx = session.beginTransaction();
        String path = request.getServletPath();
        session_user = request.getSession();
        int user_type = 0;


        for (int i = 0; i < paths.size(); i++) {
            try {
                if (path.equals(paths.get(i).toString())
                        || path.substring(0, path.toString().length() - 1).equals(paths.get(i).toString())) {
                    address = paths_jsp.get(i).toString();
                    // ---------------- /manage/category/new or edit--------------------
                    if (i == 1 || i == 3) {
                        ArrayList<String> category_errors = new ArrayList<String>();
                        int category_id = 0;
                        Category category_new = new Category();
                        Category category_edit = new Category();

                        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                        if (isMultipart) {
                            // Create a factory for disk-based file items
                            FileItemFactory factory = new DiskFileItemFactory();

                            // Create a new file upload handler
                            ServletFileUpload upload = new ServletFileUpload(factory);

                            try {
                                // Parse the request
                                List /* FileItem */ items = upload.parseRequest(request);
                                Iterator iterator = items.iterator();
                                while (iterator.hasNext()) {
                                    FileItem item = (FileItem) iterator.next();
//                                        System.out.println(item.getFieldName());
                                    if ("category_id".equals(item.getFieldName())) {
//                                        System.out.println(item.getString());
                                        category_id = Integer.parseInt(item.getString());

                                    }
                                    if (category_id != 0) {
                                        /*Edit existing category*/
                                        category_edit.setCategory_id(category_id);
                                        if (!item.isFormField()) {
                                            //check if new image is selected  or keep old image
                                            if ("category_image".equals(item.getFieldName())) {
                                                if (item.getSize() != 0) {
                                                    String fileName = item.getName();
                                                    String root = getServletContext().getRealPath("/");
                                                    File pathd = new File(root + "/../../src/main/webapp/category/uploads");
                                                    if (!pathd.exists()) {
                                                        boolean status = pathd.mkdirs();
                                                    }

                                                    File uploadedFile = new File(pathd + "/" + fileName);
//                                                    System.out.println(uploadedFile.getAbsolutePath());
                                                    item.write(uploadedFile);
                                                    category_edit.setCategory_image(fileName);
                                                } else {
                                                    /// keep old image
                                                }
                                            }
                                        } else {
                                            //Check if Category name is not empty
                                            if ("category_name".equals(item.getFieldName())) {
                                                if (item.getSize() != 0) {
                                                    category_edit.setCategory_name(item.getString());
                                                } else {
                                                    category_errors.add("No product name");
                                                }
                                            }
                                            //Check if Brand image old is not empty
                                            if ("category_image_old".equals(item.getFieldName())) {
                                                if (item.getSize() != 0) {
                                                    category_edit.setCategory_image(item.getString());
                                                } else {
                                                    category_errors.add("No old image");
                                                }
                                            }



                                        }
                                    } else {
                                        /*New category*/
                                        if (!item.isFormField()) {
                                            //check if image is selected
                                            if ("category_image".equals(item.getFieldName())) {
                                                if (item.getSize() != 0) {
                                                    String fileName = item.getName();
                                                    String root = getServletContext().getRealPath("/");
                                                    File pathd = new File(root + "/../../src/main/webapp/category/uploads");
                                                    if (!pathd.exists()) {
                                                        boolean status = pathd.mkdirs();
                                                    }

                                                    File uploadedFile = new File(pathd + "/" + fileName);
//                                                    System.out.println(uploadedFile.getAbsolutePath());
                                                    item.write(uploadedFile);
                                                    category_new.setCategory_image(fileName);
                                                } else {
                                                    category_errors.add("No image");
                                                }
                                            }
                                        } else {
                                            //Check if Category name is not empty
                                            if ("category_name".equals(item.getFieldName())) {
                                                if (item.getSize() != 0) {
                                                    category_new.setCategory_name(item.getString());
                                                } else {
                                                    category_errors.add("No Category name");
                                                }
                                            }


                                        }
                                    }
                                }
                            } catch (FileUploadException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        if (category_errors.isEmpty()) {
                            if (category_id != 0) {
                                CategoryDAO.editCategory(category_edit);
                            } else {
                                CategoryDAO.insertCategory(category_new);
                            }
                            response.sendRedirect(response.encodeRedirectURL("overview"));
                        } else {
                            // Loop through error list
//                            for (String element : product_errors) {
//                                System.out.println(element);
//                            }
                            request.setAttribute("errors", category_errors);
                            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
                            dispatcher.forward(request, response);
                        }


                    }
                }

            } catch (Exception E) {
            }
        }
    }
}
